/**
 * Copyright (c) 2008 Luciano Bustos - riaevolution.com, All Rights Reserved.
 * 
 * Contact luchyx@riaevolution.com
 *
 * See www.riaevolution.com
 * See www.riaevolution.com/blog
 *  
 * Permission is hereby granted, free of charge, to any person obtaining a copy of 
 * this software and associated documentation files (the "Software"), to deal in 
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * */
package com.riaevolution.managers
{
	import com.riaevolution.components.Alerter;
	import com.riaevolution.components.WindowPanel;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.containers.Canvas;
	import mx.events.ChildExistenceChangedEvent;
	import mx.events.CloseEvent;
	import mx.events.EffectEvent;
	import mx.events.ResizeEvent;

	public class WindowLayoutManager extends EventDispatcher
	{
		public function WindowLayoutManager()
		{
			super(this);
		}
		
		private var _container:Canvas;
		
		[Bindable]
		public function set container(value:Canvas):void {
			_container = value;
			_container.addEventListener(ChildExistenceChangedEvent.CHILD_ADD,handleChildAdded);
			_container.addEventListener(ResizeEvent.RESIZE, handleResize);
			_container.addEventListener("effectStart", lockUpdate);
			_container.addEventListener("effectEnd", unlockUpdate);
		}
		
		public function get container():Canvas {
			return _container;
		}
		
		private var canUpdateLayout:Boolean = true;
		
		private function lockUpdate(event:EffectEvent):void {
			//Alert.show(event.effectInstance.className);
			
			canUpdateLayout = false;
		}
		private function unlockUpdate(event:EffectEvent):void {
			
			canUpdateLayout = true;
			this.updatePosition();
		}
		
		private function handleResize(event:ResizeEvent):void {
			this.updatePosition();
		}
		private function handleChildAdded(event:ChildExistenceChangedEvent):void {
			
			WindowPanel(event.relatedObject).addEventListener(
				WindowPanel.MAXIMIZE, handleMaximize);
			WindowPanel(event.relatedObject).addEventListener(
				WindowPanel.RESTORE, handleRestore);
				
			WindowPanel(event.relatedObject).addEventListener(
				WindowPanel.CLOSE, handleClosePanel);
			
			this.updatePosition();
		}
		private var currentPanel:WindowPanel;
		private function handleClosePanel(event:CloseEvent):void {
			
			var msj:String = "Do you want to close "+WindowPanel(event.currentTarget).title+" pod ?";
			
			currentPanel = WindowPanel(event.currentTarget);
			
			Alerter.confirm(msj,'CLOSE_POD',okCloseMe);
			
		}
		private function okCloseMe(event:CloseEvent):void {
			if(event.detail == Alerter.OK ) {
				container.removeChild(currentPanel);
				this.updatePosition();
			}
			currentPanel = null;
		}
		private function handleMaximize(event:Event):void {
			WindowPanel(event.currentTarget).move(0,0);
			WindowPanel(event.currentTarget).width = container.width - 4;
			WindowPanel(event.currentTarget).height = container.height - 4;
		}
		private function handleRestore (event:Event):void {
			//WindowPanel(event.currentTarget).width = WindowPanel(event.currentTarget).originalWidth;
			//WindowPanel(event.currentTarget).height = WindowPanel(event.currentTarget).originalHeight;
			this.updatePosition();
		}
		private function updatePosition():void {
			if(!canUpdateLayout) return;
			//Alert.show(event.relatedObject.toString());	
			var len:Number = container.numChildren;
			var sqrt:Number = Math.floor(Math.sqrt(len));
			var numCols:Number = Math.ceil(len / sqrt);
			var numRows:Number = Math.ceil(len / numCols);
			var col:Number = 0;
			var row:Number = 0;
			var pod:WindowPanel;
			
			var tween:Boolean = false;
		
			var itemWidth:Number = Math.round(container.width / numCols - ((12 * (numCols - 1)) / numCols));
			var itemHeight:Number = Math.round(container.height / numRows - ((12 * (numRows - 1)) / numRows));
			// Layout the pods.
			for (var i:Number = 0; i < len; i++)
			{			
				if(i % numCols == 0 && i > 0)
				{
					row++;
					col = 0;
				}
				else if(i > 0)
				{
					col++;
				}
				
				var targetX:Number = col * itemWidth;
				var targetY:Number = row * itemHeight;
				
				if(col > 0) 
					targetX += 6 * col;
				if(row > 0) 
					targetY += 6 * row;
					
				targetX = Math.round(targetX);
				targetY = Math.round(targetY);
				
				pod = container.getChildAt(i) as WindowPanel;
				
				if (pod.maximized)// Window is maximized so do not include in the grid
				{
					if (tween)
					{
						//addResizeAndMoveToParallel(pod, parallel, availablePodWidth, availableMaximizedPodHeight, 0, 0);
					}
					else
					{
						pod.width = container.width;
						pod.height = container.height;
					}
					
					// Move the pod to the top of the z-index. It will not be at the top if we are coming from a saved state
					// and the pod is not the last one.
					container.setChildIndex(pod, container.numChildren - 1);
				}
				else
				{
					if (tween)
					{
						//addResizeAndMoveToParallel(pod, parallel, itemWidth, itemHeight, targetX, targetY);
					}
					else
					{
						pod.width = itemWidth;
						pod.height = itemHeight;
						pod.x = targetX;
						pod.y = targetY;
					}
				}
			}
		}
	}
}